package cn.edu.zjicm.wordsnet_d.datapersistent;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.data.StudyPlan;
import cn.edu.zjicm.wordsnet_d.data.VoicePack;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.download.DownloadVoicePackManager;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;

import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class FileManager {
	public static final String BASIC_VOICE_ZIPFILE_NAME = "inside_cet6_hf_voc.zip"; // 初级语音包
	public static final String ADVANCE_VOICE_ZIPFILE_NAME = "ielts_to_gre_voc.zip"; // 高级语音包
	// public static final String MIDDLE_SCHOOL_PHRASE_VOICE_ZIPFILE_NAME =
	// "voice_voc_phrase.zip"; // v2.10.2之前的中考高考词组合起来的语音包

	public static final String WG_ZK_VOICE_ZIPFILE_NAME = "wg_zk_voc.zip"; // 中考词组
	public static final String WG_GK_VOICE_ZIPFILE_NAME = "wg_gk_voc.zip"; // 高考词组
	public static final String WG_CET4_VOICE_ZIPFILE_NAME = "wg_cet4_voc.zip"; // 四级词组
	public static final String WG_KY_VOICE_ZIPFILE_NAME = "wg_ky_voc.zip"; // 考研词组
	public static final String WG_CET6_VOICE_ZIPFILE_NAME = "wg_cet6_voc.zip"; // 六级词组
	public static final String WG_IELTS_VOICE_ZIPFILE_NAME = "wg_ielts_voc.zip"; // 雅思词组
	public static final String WG_TOEFL_VOICE_ZIPFILE_NAME = "wg_toefl_voc.zip"; // 托福
	public static final String WG_JUNIOR_PT_VOICE_ZIPFILE_NAME = "wg_junior_pt_voc.zip"; // 初中配套
	public static final String WG_SENIOR_PT_VOICE_ZIPFILE_NAME = "wg_senior_pt_voc.zip"; // 高中配套

	public static final String BASIC_VOICE_FILE_SUFFIX_NAME = ".inside_cet6_hf_voc";
	public static final String ADVANCE_VOICE_FILE_SUFFIX_NAME = ".ielts_to_gre_voc";
	public static final String MIDDLE_SCHOOL_PHRASE_VOICE_SUFFIX_NAME = ".phrasevoc"; // v2.10.2之前的中考高考词组合起来的语音包

	public static final String WG_ZK_VOICE_SUFFIX_NAME = ".wg_zk_voc"; // 中考词组
	public static final String WG_GK_VOICE_SUFFIX_NAME = ".wg_gk_voc"; // 高考词组
	public static final String WG_CET4_VOICE_SUFFIX_NAME = ".wg_cet4_voc"; // 四级词组
	public static final String WG_KY_VOICE_SUFFIX_NAME = ".wg_ky_voc"; // 考研词组
	public static final String WG_CET6_VOICE_SUFFIX_NAME = ".wg_cet6_voc"; // 六级词组
	public static final String WG_IELTS_VOICE_SUFFIX_NAME = ".wg_ielts_voc"; // 雅思词组
	public static final String WG_TOEFL_VOICE_SUFFIX_NAME = ".wg_toefl_voc"; // 托福
	public static final String WG_JUNIOR_PT_VOICE_SUFFIX_NAME = ".wg_junior_pt_voc"; // 初中配套
	public static final String WG_SENIOR_PT_VOICE_SUFFIX_NAME = ".wg_senior_pt_voc"; // 高中配套

	public static final String IN_OLD_VOICE_SUFFIX_NAME = ".audio_absent_in_old"; // 在新版基础语音包中有但老版语音包中没有的部分单词

	public static final String VOICE_FILE_SUFFIX_NAME = ".voc"; // 音频文件后缀，也是老语音包名
	public static final String BASIC_AND_TOEFL_VOICE_FILE_SUFFIX_NAME = ".basicandtofelvoc"; // 老语言包名

	// public static final String FIRST_PART_LAST_VOICE_FILE_NAME =
	// "z/zoological" + VOICE_FILE_SUFFIX_NAME;
	// public static final String SECOND_PART_LAST_VOICE_FILE_NAME =
	// "z/zoomorphic" + VOICE_FILE_SUFFIX_NAME;
	// public static final String PHRASE_LAST_VOICE_FILE_NAME = "phrase/9529" +
	// VOICE_FILE_SUFFIX_NAME;

	public static final String VERSION_CODE_FILE_NAME = "version.xml";
	// public static final String DEFAULT_APK_FILE_NAME = "iwordnet.apk";
	public static String DEFAULT_SAVE_PATH = Environment.getExternalStorageDirectory().toString() + "/iwordnet/";
	private static String VOICE_PATH = DEFAULT_SAVE_PATH + "voice/";
	public static String DOWNLOAD_PATH = DEFAULT_SAVE_PATH + "download/";
	public static String SCREEN_SHOT_PATH = DEFAULT_SAVE_PATH + "screenshot/";
	public static String WORDGROUP = "wordgroup/";
	public static boolean isUnZiping = false;

	// 判断音频文件是否存在
	public static boolean isVoiceFileExist(Context context, OneWord word) {
		StringBuilder path = null;
		if (word.haveAudio() == 1 || word.haveAudio() == 2) {
			path = new StringBuilder();
			path.append(word.getLemma().substring(0, 1).toLowerCase(Locale.getDefault())).append("/").append(word.getLemma()).append(VOICE_FILE_SUFFIX_NAME);
		} else if (word.haveAudio() == 50) {
			String str = new String(word.getIndex_word_id() + "");
			String subFileName = str.substring(str.length() - 2, str.length());
			path = new StringBuilder();
			path.append(WORDGROUP).append(subFileName).append("/").append(word.getIndex_word_id()).append(VOICE_FILE_SUFFIX_NAME);
			LogUtil.d("音频文件为:" + word.getIndex_word_id() + ",subFileName=" + subFileName + ",path=" + path);
		} else
			return false;
		File voiceFile = new File(VOICE_PATH + path);
		if (voiceFile.exists() && voiceFile.length() > 1024)
			return true;

		checkShouldUnZip(context, word, path.toString());

		return false;
	}

	private static void checkShouldUnZip(final Context context, final OneWord word, final String path) {

		final long start = System.currentTimeMillis();

		final Handler mHandler = new Handler() {
			public void handleMessage(android.os.Message msg) {
				File file = new File((String) msg.obj);
				unZipDownloadedVoiceFile(file);
				LogUtil.d("新开线路去解压，time:" + (System.currentTimeMillis() - start));
			};
		};

		if (isUnZiping)
			return;

		LogUtil.d("进入到checkShouldUnZip");

		new Thread(new Runnable() {
			@Override
			public void run() {
				String zipFilePath = "";
				if (word.haveAudio() == 1)
					zipFilePath = DOWNLOAD_PATH + BASIC_VOICE_FILE_SUFFIX_NAME;
				else if (word.haveAudio() == 2)
					zipFilePath = DOWNLOAD_PATH + ADVANCE_VOICE_FILE_SUFFIX_NAME;
				else if (word.haveAudio() == 50) { // 说明为词组或配套单词书
					if (StudyPlan.isLearningWordBook(context) && word.getBook_id() == AppPreference.Book.BOOK_ID[AppPreference.getWordBookIndex(context)]) {
						zipFilePath = DOWNLOAD_PATH + getWGByBookId(AppPreference.getWordBookIndex(context));

					} else if (StudyPlan.isLearningPhraseBook(context) && word.getBook_id() == AppPreference.Book.BOOK_ID[AppPreference.getPhraseBookIndex(context)]) { // 在当前单词书
						zipFilePath = DOWNLOAD_PATH + getWGByBookId(AppPreference.getPhraseBookIndex(context));

					} else {
						zipFilePath = DOWNLOAD_PATH + getWGByBookId(getMinLevelBookId(word.getIndex_word_id(), context));
					}
				}

				try {
					File file = new File(zipFilePath);
					if (file.exists() && unZipSingleFile(file, getVoicePath(), path)) {
						if (!isUnZiping) {
							Message msg = Message.obtain();
							msg.obj = zipFilePath;
							mHandler.sendMessage(msg);
						}
					}
				} catch (ZipException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}).start();

	}

	// private static boolean findVoiceFileFromZip(Context context, OneWord
	// word, String path) {
	// String zipFilePath = "";
	// if (word.haveAudio() == 1)
	// zipFilePath = DOWNLOAD_PATH + BASIC_VOICE_FILE_SUFFIX_NAME;
	// else if (word.haveAudio() == 2)
	// zipFilePath = DOWNLOAD_PATH + ADVANCE_VOICE_FILE_SUFFIX_NAME;
	// else if (word.haveAudio() == 50) { // 说明为词组
	// if (word.getBook_id() ==
	// AppPreference.Book.BOOK_ID[AppPreference.getBook(context)]) { // 在当前单词书
	// zipFilePath = DOWNLOAD_PATH +
	// getWGByBookId(AppPreference.getBook(context));
	// } else {
	// zipFilePath = DOWNLOAD_PATH +
	// getWGByBookId(getMinLevelBookId(word.getIndex_word_id(), context));
	// }
	// }
	//
	// try {
	// File file = new File(zipFilePath);
	// if (file.exists() && unZipSingleFile(file, getVoicePath(), path)) {
	// if (!isUnZiping) {
	// unZipDownloadedVoiceFile(file);
	// }
	// return true;
	// }
	// } catch (ZipException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// return false;
	// }

	public static int getMinLevelBookId(int index_word_id, Context context) {
		int minLevelBookId = WordFactory.getInstance(context).getMinLevelBookIdByWordId(index_word_id); // 查找所在的语音包中最低等级的语音包
		int minLevelBookIndex = -1;
		for (int i = 0; i < AppPreference.Book.BOOK_ID.length; i++) {
			if (AppPreference.Book.BOOK_ID[i] == minLevelBookId) {
				minLevelBookIndex = i;
				break;
			}
		}
		LogUtil.d("minLevelBookIndex=" + minLevelBookIndex);
		return minLevelBookIndex;
	}

	public static String getWGByBookId(int bookIndex) {
		String wgName = null;
		if (bookIndex == 18 || bookIndex == 20) { // 中考词组,中考必备单词+词组
			wgName = WG_ZK_VOICE_SUFFIX_NAME;
		} else if (bookIndex == 19 || bookIndex == 21) { // 高考词组,高考必备单词+词组
			wgName = WG_GK_VOICE_SUFFIX_NAME;
		} else if (bookIndex == 101 || bookIndex == 102) { // 四级词组，四级单词+词组
			wgName = WG_CET4_VOICE_SUFFIX_NAME;
		} else if (bookIndex >= 103 && bookIndex <= 105) { // 考研词组，考研补充词组，考研单词+词组
			wgName = WG_KY_VOICE_SUFFIX_NAME;
		} else if (bookIndex == 106 || bookIndex == 107) { // 六级词组，六级单词+词组
			wgName = WG_CET6_VOICE_SUFFIX_NAME;
		} else if (bookIndex == 108 || bookIndex == 109) { // 雅思词组，雅思单词+词组
			wgName = WG_IELTS_VOICE_SUFFIX_NAME;
		} else if (bookIndex == 110 || bookIndex == 111) { // 托福词组，托福单词+词组
			wgName = WG_TOEFL_VOICE_SUFFIX_NAME;
		} else if (bookIndex >= 23 && bookIndex <= 44 || bookIndex >= 57 && bookIndex <= 81) { // 初中配套
			wgName = WG_JUNIOR_PT_VOICE_SUFFIX_NAME;
		} else if (bookIndex >= 45 && bookIndex <= 56 || bookIndex >= 82 && bookIndex <= 100) { // 高中配套
			wgName = WG_SENIOR_PT_VOICE_SUFFIX_NAME;
		}
		return wgName;
	}

	public static File getVoiceFile(OneWord word) {
		String path = "";
		if (word.haveAudio() == 1 || word.haveAudio() == 2)
			path = word.getLemma().substring(0, 1).toLowerCase(Locale.getDefault()) + "/" + word.getLemma() + VOICE_FILE_SUFFIX_NAME;
		else if (word.haveAudio() == 50) {
			String str = new String(word.getIndex_word_id() + "");
			String subFileName = str.substring(str.length() - 2, str.length());
			path = WORDGROUP + subFileName + "/" + word.getIndex_word_id() + VOICE_FILE_SUFFIX_NAME;
		}
		return new File(VOICE_PATH + path);
	}

	// 学习当前单词书，是否还要需要的语音包未下载 --注释by ct v2.11.0
	// public static boolean hasNotDownloadedVoicePack(Context context, boolean
	// forPrompt) {
	// return getDownloadVoicePackList(AppPreference.getBook(context),
	// forPrompt, true).size() > 0;
	// }

	public static boolean hasNotDownloadedVoicePack(Context context, boolean forPrompt) {
		return getDownloadVoicePackList(forPrompt, true, context).size() > 0;
	}

	// 根据正在学习的单词书，生成需下载的语音包名称列表
	public static Set<String> getDownloadVoicePackList(boolean forPrompt, boolean shouldDownloadBasicPack, Context context) {
		int wordBookIndex = AppPreference.getWordBookIndex(context);
		int phraseBookIndex = AppPreference.getPhraseBookIndex(context);

		Set<String> voicePackNameList = new TreeSet<String>();

		voicePackNameList.addAll(getWordDownloadList(wordBookIndex, forPrompt));
		voicePackNameList.addAll(getPhraseDownloadList(phraseBookIndex, forPrompt));

		if (shouldDownloadBasicPack && shouldDownloadVoicePack(VoicePack.basicPack, forPrompt, true))
			voicePackNameList.add(VoicePack.basicPack.getName());

		return voicePackNameList;
	}

	public static Set<String> getDownloadVoicePackList(int bookIndex, boolean forPrompt, boolean shouldDownloadBasicPack, int lemmaType) {
		if (lemmaType == OneWord.LEMMA_TYPE_WORD)
			return getWordDownloadList(bookIndex, forPrompt);
		else
			return getPhraseDownloadList(bookIndex, forPrompt);
	}

	/**
	 * 根据词组bookIndex获取需要下载的语音包
	 * 
	 * @param phraseBookIndex
	 * @param forPrompt
	 * @return
	 */
	private static Set<String> getPhraseDownloadList(int phraseBookIndex, boolean forPrompt) {
		Set<String> voicePackNameList = new TreeSet<String>();
		if (phraseBookIndex == 18 || phraseBookIndex == 20) { // 中考词组,中考必备单词+词组,需下载中考词组语音包和基础词库语音包
			if (shouldDownloadVoicePack(VoicePack.wgZKPack, forPrompt, true))
				voicePackNameList.add(VoicePack.wgZKPack.getName());

		} else if (phraseBookIndex == 19 || phraseBookIndex == 21) { // 高考词组,高考必备单词+词组
			if (shouldDownloadVoicePack(VoicePack.wgGKPack, forPrompt, true))
				voicePackNameList.add(VoicePack.wgGKPack.getName());

		} else if (phraseBookIndex == 101 || phraseBookIndex == 102) { // 四级词组，四级单词+词组
			if (shouldDownloadVoicePack(VoicePack.wgCET4Pack, forPrompt, true))
				voicePackNameList.add(VoicePack.wgCET4Pack.getName());

		} else if (phraseBookIndex >= 103 && phraseBookIndex <= 105) { // 考研词组，考研补充词组，考研单词+词组
			if (shouldDownloadVoicePack(VoicePack.wgKYPack, forPrompt, true))
				voicePackNameList.add(VoicePack.wgKYPack.getName());

		} else if (phraseBookIndex == 106 || phraseBookIndex == 107) { // 六级词组，六级单词+词组
			if (shouldDownloadVoicePack(VoicePack.wgCET6Pack, forPrompt, true))
				voicePackNameList.add(VoicePack.wgCET6Pack.getName());

		} else if (phraseBookIndex == 108 || phraseBookIndex == 109) { // 雅思词组，雅思单词+词组,需下载基础+高级+对应词组包
			if (shouldDownloadVoicePack(VoicePack.wgIELTSPack, forPrompt, true))
				voicePackNameList.add(VoicePack.wgIELTSPack.getName());
			if (shouldDownloadVoicePack(VoicePack.advancePack, forPrompt, true))
				voicePackNameList.add(VoicePack.advancePack.getName());

		} else if (phraseBookIndex == 110 || phraseBookIndex == 111) { // 托福词组，托福单词+词组
			if (shouldDownloadVoicePack(VoicePack.wgTOEFLPack, forPrompt, true))
				voicePackNameList.add(VoicePack.wgTOEFLPack.getName());
			if (shouldDownloadVoicePack(VoicePack.advancePack, forPrompt, true))
				voicePackNameList.add(VoicePack.advancePack.getName());
		}
		return voicePackNameList;
	}

	private static Set<String> getWordDownloadList(int wordBookIndex, boolean forPrompt) {
		Set<String> voicePackNameList = new TreeSet<String>();
		if (wordBookIndex >= 23 && wordBookIndex <= 44 || wordBookIndex >= 57 && wordBookIndex <= 81) { // 初中配套
			if (shouldDownloadVoicePack(VoicePack.wgJuniorPack, forPrompt, true))
				voicePackNameList.add(VoicePack.wgJuniorPack.getName());

		} else if (wordBookIndex >= 45 && wordBookIndex <= 56 || wordBookIndex >= 82 && wordBookIndex <= 100) { // 高中配套
			if (shouldDownloadVoicePack(VoicePack.wgSeniorPack, forPrompt, true))
				voicePackNameList.add(VoicePack.wgSeniorPack.getName());
		} else if (wordBookIndex >= 8 && wordBookIndex <= 10 || wordBookIndex == 22 || wordBookIndex == 13 || wordBookIndex == 14) { // 雅思、托福、GRE、专四、专八、新概念3、新概念4等,下载基础包+高级包
			if (shouldDownloadVoicePack(VoicePack.advancePack, forPrompt, true))
				voicePackNameList.add(VoicePack.advancePack.getName());
		}
		return voicePackNameList;
	}

	// 生成当缺少某单词音频文件时，应下载的语音包名称列表
	public static Set<String> getDownloadVoicePackList(OneWord word, Context context) {
		Set<String> voicePackNameList = new TreeSet<String>();
		if (word.haveAudio() == 1 && shouldDownloadVoicePack(VoicePack.basicPack, false, false))
			voicePackNameList.add(VoicePack.basicPack.getName());
		else if (word.haveAudio() == 2 && shouldDownloadVoicePack(VoicePack.advancePack, false, false))
			voicePackNameList.add(VoicePack.advancePack.getName());
		else if (word.haveAudio() == 50) { // 50表示词组或者配套单词书
			if (StudyPlan.isLearningWordBook(context) && word.getBook_id() == AppPreference.Book.BOOK_ID[AppPreference.getWordBookIndex(context)]) {// 在当前单词书
				voicePackNameList.addAll(getDownloadVoicePackList(false, false, context));

			} else if (StudyPlan.isLearningPhraseBook(context) && word.getBook_id() == AppPreference.Book.BOOK_ID[AppPreference.getPhraseBookIndex(context)]) {// 在当前单词书
				voicePackNameList.addAll(getDownloadVoicePackList(false, false, context));

			} else {
				voicePackNameList.addAll(getDownloadVoicePackList(getMinLevelBookId(word.getIndex_word_id(), context), false, false, word.getLemma_type()));
			}
		}

		return voicePackNameList;
	}

	// forPrompt: true 判断语音包未下载并且没有加入下载队列; false 只判断语音包是否未下载
	public static boolean shouldDownloadVoicePack(VoicePack voicePack, boolean forPrompt, boolean compatibleForOldVersion) {
		if (forPrompt)
			return !isZipFileExist(voicePack, compatibleForOldVersion) && !DownloadVoicePackManager.isDownloadManagerExist(voicePack.getName());
		else
			return !isZipFileExist(voicePack, compatibleForOldVersion);
	}

	// 判断某个语音包是否已下载
	// compatibleForOldVersion为true,老版的语音包.voc或.basicandtofelvoc视为基础语音包;
	public static boolean isZipFileExist(VoicePack voicePack, boolean compatibleForOldVersion) {
		String zipFile1 = null, zipFile2 = null;
		if (voicePack.getFileName().equals(WG_ZK_VOICE_SUFFIX_NAME) || voicePack.getFileName().equals(WG_GK_VOICE_SUFFIX_NAME)) { // 中考和高考词组
			zipFile1 = DOWNLOAD_PATH + voicePack.getFileName();
			zipFile2 = DOWNLOAD_PATH + MIDDLE_SCHOOL_PHRASE_VOICE_SUFFIX_NAME;
		} else {
			zipFile1 = DOWNLOAD_PATH + voicePack.getFileName();
		}

		if (zipFile2 != null) {
			File file2 = new File(zipFile2);
			if (file2.exists() && file2.length() >= 5 * 1024 * 1024) { // 如果之前已经下过中考高考词组语言包(大小5M)，就不用再下载
				return true;
			}
		}

		File file = new File(zipFile1);
		if (file.exists() && file.length() > (int) voicePack.getShowSize() * 1024 * 1024) {
			return true;
		} else if (compatibleForOldVersion && voicePack.getFileName().equals(BASIC_VOICE_FILE_SUFFIX_NAME)) {
			file = new File(DOWNLOAD_PATH + VOICE_FILE_SUFFIX_NAME);
			if (file.exists() && file.length() > (int) voicePack.getShowSize() * 1024 * 1024)
				return true;
			file = new File(DOWNLOAD_PATH + BASIC_AND_TOEFL_VOICE_FILE_SUFFIX_NAME);
			if (file.exists() && file.length() > (int) voicePack.getShowSize() * 1024 * 1024)
				return true;
			return false;
		} else {
			return false;
		}
	}

	public static String getZipFilePath(VoicePack voicePack) {
		File zipDir = new File(DOWNLOAD_PATH);
		if (!zipDir.exists()) {
			zipDir.mkdirs();
		}
		return DOWNLOAD_PATH + voicePack.getFileName();
	}

	public static boolean isZipFileExist(String fileName) {
		String zipFile = DOWNLOAD_PATH + fileName;
		File file = new File(zipFile);
		if (file.exists()) {
			return true;
		} else {
			return false;
		}
	}

	public static String getZipFilePath(String fileName) {
		File zipDir = new File(DOWNLOAD_PATH);
		if (!zipDir.exists()) {
			zipDir.mkdirs();
		}
		return DOWNLOAD_PATH + fileName;
	}

	public static String getVoicePath() {
		File voiceDir = new File(VOICE_PATH);
		if (!voiceDir.exists()) {
			voiceDir.mkdirs();
		}
		return VOICE_PATH;
	}

	public static String getScreenShotPath() {
		File downloadDir = new File(SCREEN_SHOT_PATH);
		if (!downloadDir.exists()) {
			downloadDir.mkdirs();
		}
		return SCREEN_SHOT_PATH;
	}

	public static String renameDownloadCompelateFile(File ncFile) {
		if (ncFile != null && ncFile.getAbsolutePath().endsWith(".nc")) {
			String path = ncFile.getAbsolutePath().substring(0, ncFile.getAbsolutePath().length() - 3);
			File completeFile = new File(path);
			ncFile.renameTo(completeFile);
			return path;
		}
		return null;
	}

	public static boolean unZipSingleFile(File zipFile, String folderPath, String lemma) throws ZipException, IOException {

		byte[] buf = new byte[102400];
		ZipFile zfile = new ZipFile(zipFile);
		ZipEntry ze = null;
		ze = zfile.getEntry(lemma);
		if (ze == null) {
			Log.e("upSingleZipFile", "voice file not exists:" + lemma);
			return false;
		} else {
			OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(folderPath, ze.getName())));
			InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
			int readLen = 0;
			while ((readLen = is.read(buf, 0, buf.length)) != -1) {
				os.write(buf, 0, readLen);
			}
			is.close();
			os.close();
			Log.e("upSingleZipFile", lemma);
			return true;
		}
	}

	public static void unZipDownloadedVoiceFile(final File downloadFile) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				isUnZiping = true;
				try {
					FileManager.unZipFile(downloadFile, FileManager.getVoicePath());
				} catch (ZipException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				isUnZiping = false;
			}
		}).start();
		isUnZiping = false;
	}

	/**
	 * 解压缩功能. 将zipFile文件解压到folderPath目录下.
	 * 
	 * @throws Exception
	 */
	public static void unZipFile(File zipFile, String folderPath) throws ZipException, IOException {
		// public static void upZipFile() throws Exception{
		Log.e("upZipFile:" + zipFile.getName(), "开始解压缩");
		long start = System.currentTimeMillis();
		ZipFile zfile = new ZipFile(zipFile);
		Enumeration zList = zfile.entries();
		ZipEntry ze = null;
		int i = 0;
		byte[] buf = new byte[102400];
		while (zList.hasMoreElements()) {
			i++;
			// if (i == 3000)
			// break;
			ze = (ZipEntry) zList.nextElement();
			if (ze.isDirectory()) {
				// Log.w("upZipFile", "ze.getName() = " + ze.getName() +
				// "--------" + ze.getSize());
				String dirstr = folderPath + ze.getName();
				// dirstr.trim();
				dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
				// Log.w("upZipFile", "str = " + dirstr);
				File f = new File(dirstr);
				f.mkdir();
				continue;
			}
			// Log.w("upZipFile:" + zipFile.getName(), "ze.getName() = " +
			// ze.getName());
			OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(folderPath, ze.getName())));
			InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
			int readLen = 0;
			while ((readLen = is.read(buf, 0, buf.length)) != -1) {
				os.write(buf, 0, readLen);
			}
			is.close();
			os.close();
		}
		zfile.close();
		long end = System.currentTimeMillis();
		Log.e("upZipFile:" + zipFile.getName(), "finish,总共解压" + i + "个单词,用时" + (end - start));
	}

	/**
	 * 给定根目录，返回一个相对路径所对应的实际文件名.
	 * 
	 * @param baseDir
	 *            指定根目录
	 * @param absFileName
	 *            相对路径名，来自于ZipEntry中的name
	 * @return java.io.File 实际的文件
	 */
	public static File getRealFileName(String baseDir, String absFileName) {
		String[] dirs = absFileName.split("/");
		File ret = new File(baseDir);
		String substr = null;
		if (dirs.length > 1) {
			for (int i = 0; i < dirs.length - 1; i++) {
				substr = dirs[i];
				try {
					// substr.trim();
					substr = new String(substr.getBytes("8859_1"), "GB2312");

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ret = new File(ret, substr);
			}
			// Log.d("upZipFile", "1ret = " + ret);
			if (!ret.exists())
				ret.mkdirs();
			substr = dirs[dirs.length - 1];
			try {
				// substr.trim();
				substr = new String(substr.getBytes("8859_1"), "GB2312");
				// substr = substr.substring(0, substr.length()-4) + ".voc";
				// //将mp3后缀改为voc
				// Log.d("upZipFile", "substr = " + substr);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ret = new File(ret, substr);
			// Log.d("upZipFile", "2ret = " + ret);
			return ret;
		}
		return ret;
	}

	public static void movePhraseFile() {
		long startTime = System.currentTimeMillis();
		File oldPhraseFile = new File(VOICE_PATH + "/phrase");
		if (oldPhraseFile.exists() && oldPhraseFile.length() > 0) { // 存在phrase文件夹
			LogUtil.d("phrase文件夹存在");

			File newPhraseFile = new File(VOICE_PATH + WORDGROUP);
			if (!newPhraseFile.exists()) { // 创建wordgroup目录
				newPhraseFile.mkdirs();

				for (int i = 0; i < 100; i++) { // 创建100个子文件夹
					String subFileName = i < 10 ? ("0" + i) : ("" + i);
					String subFilePath = newPhraseFile.getPath() + "/" + subFileName;
					File subFile = new File(subFilePath);
					subFile.mkdirs();
				}

				LogUtil.d("创建100个子文件夹成功");

				File[] oldPhraseVoiceFile = oldPhraseFile.listFiles();
				LogUtil.d("oldPhraseVoiceFile.size=" + oldPhraseVoiceFile.length);

				for (File file : oldPhraseVoiceFile) {
					String name = file.getName();
					String subName = name.substring(name.length() - 6, name.length() - 4);
					String newPath = newPhraseFile.getPath() + "/" + subName + "/" + name;
					copyFile(file.getPath(), newPath);
					delFile(file.getPath());
				}
				oldPhraseFile.delete();
			}

		}

		LogUtil.e("迁移phrase文件夹耗时:" + (System.currentTimeMillis() - startTime));
	}

	public static void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.close();
			}
		} catch (Exception e) {
			System.out.println("复制单个文件操作出错 ");
			e.printStackTrace();

		}
	}

	public static void delFile(String oldPath) {
		try {
			File myDelFile = new File(oldPath);
			myDelFile.delete();

		} catch (Exception e) {
			System.out.println("删除文件操作出错 ");
			e.printStackTrace();

		}
	}

	// public static final String APPEND_VOICE_FILE_SUFFIX_NAME = ".appendvoc";
	// public static final String APPEND_VOICE_FILE_SUFFIX_NAME1 =
	// ".appendvoc1";
	// public static final String PHRASE_VOICE_FILE_SUFFIX_NAME = ".phrasevoc";

	// private static Context mContext;
	//
	// FileManager(Context mContext) {
	// this.mContext = mContext;
	// }

	/**
	 * 粗略判断读音文件是否存在
	 * 
	 * @return
	 */
	// public static boolean isVoiceFileExist(){
	// File voiceDir = new File(VOICE_PATH);
	// if(!voiceDir.exists())return false;
	// File VoicDirA = new File(VOICE_PATH + "a/");
	// if(!VoicDirA.exists())return false;
	// File VoicDirZ = new File(VOICE_PATH + "z/");
	// if(!VoicDirZ.exists())return false;
	// File VoicZoom = new File(VOICE_PATH + LAST_VOICE_FILE_NAME);//最后一个音频文件
	// if(!VoicZoom.exists())return false;
	// return true;
	// }

	// // 要下载的语音包文件名
	// // 1不存在基础语言包时，下载基础+托福语音包
	// // 2基础语音包存在，需要下载托福语音包，则下载托福语音包
	// public static String getVoiceZipfile(Context context) {
	// if (!isBasicZipFileExist())
	// return BASIC_AND_TOEFL_VOICE_ZIPFILE_NAME;
	// if (AppPreference.getBook(context) == 9 && !isTofelZipFileExist())
	// return TOEFL_VOICE_ZIPFILE_NAME;
	// return null;
	// }
	//
	// public static String getDownloadedVoiceFileName(Context context) {
	// if (!isBasicZipFileExist())
	// return BASIC_AND_TOEFL_VOICE_FILE_SUFFIX_NAME;
	// if (AppPreference.getBook(context) == 9 && !isTofelZipFileExist())
	// return TOEFL_VOICE_FILE_SUFFIX_NAME;
	// return null;
	// }
	//
	// public static int getDownloadedVoiceFileSize(Context context) {
	// if (!isBasicZipFileExist())
	// return 16;
	// if (AppPreference.getBook(context) == 9 && !isTofelZipFileExist())
	// return 2;
	// return 0;
	// }
	//
	// public static String getDownloadedVoiceFileSizeString(Context context) {
	// if (!isBasicZipFileExist())
	// return "16.3";
	// if (AppPreference.getBook(context) == 9 && !isTofelZipFileExist())
	// return "2.5";
	// return "0";
	// }
	//
	// // 判断压缩包是否存在
	// public static boolean isZipFileExist(Context context) {
	// if (!isBasicZipFileExist())
	// return false;
	// if (AppPreference.getBook(context) == 9) // 是否是托福单词
	// return isTofelZipFileExist();
	// return true;
	// }
	//
	// // 判断压缩包是否存在, 基础音频包或者基础+托福音频包
	// public static boolean isBasicZipFileExist() {
	// String zipFile = DOWNLOAD_PATH + VOICE_FILE_SUFFIX_NAME;
	// File file = new File(zipFile);
	// if (file.exists() && file.length() > 12 * 1024 * 1024)
	// return true;
	// zipFile = DOWNLOAD_PATH + BASIC_AND_TOEFL_VOICE_FILE_SUFFIX_NAME;
	// file = new File(zipFile);
	// if (file.exists() && file.length() > 16 * 1024 * 1024)
	// return true;
	// return false;
	// }
	//
	// // 判断包含托福语音的压缩包是否存在, 托福音频包或者基础+托福音频包
	// public static boolean isTofelZipFileExist() {
	// String zipFile = DOWNLOAD_PATH + TOEFL_VOICE_FILE_SUFFIX_NAME;
	// File file = new File(zipFile);
	// if (file.exists() && file.length() > 2 * 1024 * 1024)
	// return true;
	// zipFile = DOWNLOAD_PATH + BASIC_AND_TOEFL_VOICE_FILE_SUFFIX_NAME;
	// file = new File(zipFile);
	// if (file.exists() && file.length() > 16 * 1024 * 1024)
	// return true;
	// return false;
	// }

	// public static String getDownloadingVoicePath(Context context) {
	// File downloadDir = new File(DOWNLOAD_PATH);
	// if (!downloadDir.exists()) {
	// downloadDir.mkdirs();
	// }
	// return DOWNLOAD_PATH + getDownloadedVoiceFileName(context) + ".nc";
	// }
	//
	// public static File getDownloadedVoiceFile(Context context) {
	// File downloadFile = new File(DOWNLOAD_PATH +
	// getDownloadedVoiceFileName(context));
	// return downloadFile;
	// }

	// public static boolean isFirstPartVoiceFileExist() {
	// File voiceDir = new File(VOICE_PATH);
	// if (!voiceDir.exists())
	// return false;
	// for (char c = 'a'; c <= 'z'; c++) {
	// File subVoicDir = new File(VOICE_PATH + c + "/");
	// if (!subVoicDir.exists())
	// return false;
	// }
	// File VoicZoom = new File(VOICE_PATH + FIRST_PART_LAST_VOICE_FILE_NAME);//
	// 最后一个音频文件
	// if (!VoicZoom.exists())
	// return false;
	// return true;
	// }
	//
	// public static boolean isSecondPartVoiceFileExist() {
	// File VoicZoom = new File(VOICE_PATH +
	// SECOND_PART_LAST_VOICE_FILE_NAME);// 最后一个音频文件
	// if (!VoicZoom.exists())
	// return false;
	// return true;
	// }
	//
	// public static boolean isPhraseVoiceFileExist() {
	// File VoicZoom = new File(VOICE_PATH + PHRASE_LAST_VOICE_FILE_NAME); //
	// 最后一个音频文件
	// if (!VoicZoom.exists())
	// return false;
	// return true;
	// }

	// public static File getAppendVoiceFile() {
	// File downloadFile = new File(DOWNLOAD_PATH +
	// APPEND_VOICE_FILE_SUFFIX_NAME);
	// return downloadFile;
	// }
	//
	// public static File getAppendVoiceFile1() {
	// File downloadFile = new File(DOWNLOAD_PATH +
	// APPEND_VOICE_FILE_SUFFIX_NAME1);
	// return downloadFile;
	// }
	//
	// public static File getPhraseVoiceFile() {
	// File downloadFile = new File(DOWNLOAD_PATH +
	// PHRASE_VOICE_FILE_SUFFIX_NAME);
	// return downloadFile;
	// }
	//
	// public static String getAppendVoicePath() {
	// File downloadDir = new File(DOWNLOAD_PATH);
	// if (!downloadDir.exists()) {
	// downloadDir.mkdirs();
	// }
	// return DOWNLOAD_PATH + APPEND_VOICE_FILE_SUFFIX_NAME + ".nc";
	// }
	//
	// public static String getAppendVoicePath1() {
	// File downloadDir = new File(DOWNLOAD_PATH);
	// if (!downloadDir.exists()) {
	// downloadDir.mkdirs();
	// }
	// return DOWNLOAD_PATH + APPEND_VOICE_FILE_SUFFIX_NAME1 + ".nc";
	// }
	//
	// public static String getPhraseVoicePath() {
	// File downloadDir = new File(DOWNLOAD_PATH);
	// if (!downloadDir.exists()) {
	// downloadDir.mkdirs();
	// }
	// return DOWNLOAD_PATH + PHRASE_VOICE_FILE_SUFFIX_NAME + ".nc";
	// }
}
